<?php

namespace plugin\thinkphp\grid\Driver;


use plugin\thinkphp\grid\Filter;
use plugin\thinkphp\grid\Jobs\Export;
use ExAdmin\ui\component\grid\grid\Grid;
use ExAdmin\ui\contract\GridAbstract;
use ExAdmin\ui\response\Message;
use ExAdmin\ui\response\Response;
use plugin\thinkphp\traits\SoftDeleteHelp;
use think\db\Query;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Request;
use think\Model;
use think\model\concern\SoftDelete;

/**
 * @property Model $repository
 */
class Eloquent extends GridAbstract
{
    use SoftDeleteHelp;
    /**
     * @var Grid
     */
    protected $grid;
    /**
     * @var Query
     */
    protected $builder;


    protected $tableField = [];

    public function initialize(Grid $grid, $repository)
    {
        parent::initialize($grid, $repository); // TODO: Change the autogenerated stub
        $this->builder = $this->repository->db();
        if ($this->trashed() && $this->grid->isTrashed()) {
            $this->builder = $this->repository->onlyTrashed();
        }
        $this->setPk($this->repository->getPk());
    }

    /**
     * 是否有回收站
     * @return bool
     */
    public function trashed(): bool
    {
        return $this->isTrashed($this->repository);
    }



    /**
     * 恢复数据
     * @param array $ids 恢复id
     * @return Message
     */
    public function restore(array $ids): Message
    {
        $this->repository->restore([[$this->getPk(),'in' ,$ids]]);
        return message_success(admin_trans('grid.restore_success'));
    }
    /**
     * 删除
     * @param array $ids 删除id
     * @param bool $all 是否删除全部
     * @return mixed
     */
    public function delete(array $ids,bool $all = false): Message
    {
        $arg = $all ?: $ids;
        $result = $this->dispatchEvent('deling',[$arg]);
        if($result instanceof Message){
            return $result;
        }
        if ($this->grid->isTrashed()) {
            $result = $this->builder
                ->when($all,function ($query) {
                    $query->whereRaw('1=1');
                },function ($query) use($ids){
                    $query->whereIn($this->getPk(), $ids);
                })
                ->removeOption('field')
                ->removeOption('soft_delete')->delete();
        } else {
            $result = $this->builder
                ->when($this->trashed(),function ($query){
                    $this->useSoftDelete($this->repository,$query);
                })
                ->when($all,function ($query){
                    $query->whereRaw('1=1');
                },function ($query) use($ids){
                    $query->whereIn($this->getPk(), $ids);
                })
                ->removeOption('field')
                ->delete();
        }
        $deletedResult = $this->dispatchEvent('deleted',[$arg]);
        if($deletedResult instanceof Message){
            return $deletedResult;
        }
        if ($result) {
            return message_success(admin_trans('grid.delete_success'));
        }
        return message_error(admin_trans('grid.delete_error'));
    }

    /**
     * 拖拽排序
     * @param int $id 排序id
     * @param int $sort 排序位置
     * @param string $field 字段
     * @return Message
     */
    public function dragSort($id, int $sort, string $field): Message
    {
        $result = $this->dispatchEvent('sorting', [$id,$sort,$field]);
        if ($result instanceof Message) {
            return $result;
        }
        $pk = $this->getPk();

        $selectRaw = "{$pk},(@rownum := @rownum+1),case when @rownum = {$sort} then @rownum := @rownum+1 else @rownum := @rownum end AS rownum";

        $sortSql = Db::connect($this->repository->getConnection())->table("(SELECT @rownum := -1) r," . $this->repository->getTable())
            ->fieldRaw($selectRaw)
            ->order($field)
            ->where($pk, '<>', $id)
            ->buildSql();

        $this->repository->where($pk, $id)->update([$field => $sort]);

        Db::connect($this->repository->getConnection())->execute("update {$this->repository->getTable()} inner join ({$sortSql}) a on a.{$pk}={$this->repository->getTable()}.{$pk} set `{$field}`=a.rownum");

        return message_success(admin_trans('grid.sort_success'));
    }

    /**
     * 输入框排序
     * @param int $id 排序id
     * @param int $sort 排序位置
     * @param string $field 字段
     * @return Message
     */
    public function inputSort($id, int $sort, string $field): Message
    {
        $result = $this->dispatchEvent('sorting', [$id,$sort,$field]);
        if ($result instanceof Message) {
            return $result;
        }
        $this->repository->where($this->getPk(), $id)->update([$field => $sort]);
        return message_success(admin_trans('grid.sort_success'));
    }

    /**
     * 更新
     * @deprecated
     * @param array $ids 更新条件id集合
     * @param array $data 更新数据
     * @return Message
     */
    public function update(array $ids, array $data): Message
    {

        $result = $this->dispatchEvent('updateing',[$ids, $data]);
        if($result instanceof Message){
            return $result;
        }
        $this->repository->whereIn($this->getPk(), $ids)->update($data);
        $result = $this->dispatchEvent('updated',[$ids, $data]);
        if($result instanceof Message){
            return $result;
        }
        return message_success(admin_trans('grid.update_success'));
    }

    /**
     * 表格列触发排序
     * @param string $field 字段
     * @param string $sort 排序 asc desc
     * @return mixed
     */
    public function tableSort($field, $sort)
    {
        $this->builder->removeOption('order')->order($field, $sort);
    }

    /**
     * 筛选
     * @param array $rule
     */
    public function filter(array $rule)
    {
       new Filter($this->builder,$rule);
    }
    /**
     * 快捷搜索
     * @param string $keyword 关键词
     * @param string|array|\Closure $search 搜索设置
     * @return mixed
     */
    public function quickSearch($keyword, $search)
    {
        if ($keyword === '' || $keyword === null) {
            return;
        }
        if ($search instanceof \Closure) {
            $this->builder->where(function ($query) use ($search, $keyword) {
                call_user_func_array($search, [$query, $keyword]);
            });
        }
        if (is_string($search)) {
            $search = [$search];
        }
        if (is_array($search)) {
            $this->builder->where(function ($query) use ($search, $keyword) {
                foreach ($search as $field) {
                    $query->whereOr($field, "LIKE", "%$keyword%");
                }
            });
        } elseif (is_null($search)) {

            $this->builder->where(function ($query) use ($keyword) {
                $tableField[$this->repository->getTable()] = $this->getTableField();

                $table = $this->repository->getTable();
                $wheres = [];
                foreach ($this->grid->getColumns() as $column) {
                    $field = $column->attr('dataIndex');
                    $using = $column->using;
                    $fields = explode('.', $field);
                    if (count($fields) > 1) {
                        $field = array_pop($fields);
                        $model = $this->repository;
                        foreach ($fields as $relation) {
                            $model = $model->$relation()->getModel();
                        }

                        if (!array_key_exists($model->getTable(), $tableField)) {
                            $tableField[$model->getTable()] = Db::connect($this->repository->getConnection())->getFields($model->getTable());
                        }
                        $relation = implode('.', $fields);
                        $relationTableField = $tableField[$model->getTable()];
                        $where = $this->buildOrWhere($field, $relationTableField, $using, $keyword);
                    } else {
                        $relation = $table;
                        $where = $this->buildOrWhere($field, $tableField[$table], $using, $keyword);
                    }

                    if (count($where) > 0) {
                        if (isset($wheres[$relation])) {
                            $wheres[$relation] = array_merge($wheres[$relation], $where);
                        } else {
                            $wheres[$relation] = $where;
                        }
                    }
                }
                $filter = new Filter($query);

                foreach ($wheres as $relation => $where) {
                    if ($relation == $table) {
                        $this->addOrWhereBinding($query, $where);
                    } else {
                        $filter->whereRelation($relation,$query,function ($q) use ($where) {
                            $q->where(function ($query) use ($where) {
                                $this->addOrWhereBinding($query, $where);
                            });
                        },'OR');
                    }
                }
            });

        }
    }

    protected function addOrWhereBinding($query, $wheres)
    {
        foreach ($wheres as $where) {
            $query->whereOr(...$where);
        }
    }
    protected function parseDateTime($type,$originValue){
        if (in_array($type,['datetime','timestamp','date'])) {
            $value = strtotime($originValue);
            if($value === false){
                return $value;
            }
            if ('date' == $type) {
                $value = date('Y-m-d', $value);
            }else{
                $value = date('Y-m-d H:i:s', $value);
            }
        }else{
            $value = $originValue;
        }
        return $value;
    }
    protected function buildOrWhere($field, $tableField, $using, $keyword)
    {
        $where = [];
        if (array_key_exists($field, $tableField)) {
            if (count($using) > 0) {
                foreach ($using as $key => $value) {
                    if (strpos($value, $keyword) !== false) {
                        $where[] = [$field, "=", $key];
                    }
                }
            } else {
                $value = $this->parseDateTime($tableField[$field]['type'],$keyword);
                if($value !== false){
                    if($keyword == $value){
                        $where[] = [$field, "LIKE", "%$keyword%"];
                    }else{
                        $where[] = [$field, "=", $value];
                    }
                }
            }
        }
        return $where;
    }

    /**
     * 预关联加载
     */
    protected function with()
    {
        $eagerLoad = $this->builder->getOptions('with') ?? [];
        $relations = [];
        foreach ($this->grid->getColumns() as $column) {
            $field = $column->attr('dataIndex');
            $fields = explode('.', $field);
            if (count($fields) > 1) {
                array_pop($fields);
                $relation = implode('.', $fields);
                if(method_exists($this->repository, $relation)) {
                    $relations[] = $relation;
                }
            }
        }
        $relations = array_merge($relations, $eagerLoad);
        if (count($relations) > 0) {
            $this->builder->with($relations);
        }
    }

    /**
     * 数据源
     * @param int $page 第几页
     * @param int $size 分页大小
     * @param bool $hidePage 是否分页
     * @return mixed
     */
    public function data(int $page, int $size, bool $hidePage)
    {
        $sql   = $this->builder->buildSql();
        $sql   = "SELECT COUNT(*) FROM {$sql} userCount";
        $res   = Db::connect($this->repository->getConnection())->query($sql);
        $count = $res[0]['COUNT(*)'];
        $this->setTotal($count);
        $this->with();
        if ($hidePage) {
            return $this->builder->select();
        } else {
            return $this->builder->page($page, $size)->select();
        }
    }

    /**
     * 返回总条数
     * @return int
     */
    public function total(): int
    {
        return $this->total;
    }

    /**
     * 导出数据
     * @param array $selectIds 导出选中id
     * @param array $columns 导出列
     * @param bool $all 是否导出全部
     * @return Response
     */
    public function export(array $selectIds, array $columns, bool $all): Response
    {
        $progressKey = Request::param('ex_admin_progress_key', uniqid());
        $export = $this->grid->getExport();
        $export->setProgressKey($progressKey);
        try {
            if (Request::param('ex_admin_queue')) {
                Export::dispatch(Request::all() + ['ex_admin_progress_key' => $progressKey]);
            } else {
                $columns = array_column($columns, 'title', 'dataIndex');
                $this->builder->when(!$all, function (Query $builder) use ($selectIds) {
                    $builder->whereIn($this->getPk(),$selectIds);
                });
                $count = $this->builder->count();
                $export->columns($columns)->count($count);
                $this->builder->chunk(500, function ($data) use ($export) {
                    $data = $this->grid->parseColumn($data, true);
                    $export->write($data, function ($export) {
                        $export->save(Filesystem::disk('public')->path(''));
                        return Filesystem::disk('public')->url($export->getFilename() . '.' . $export->getExtension());
                    });
                });
            }
        } catch (\Throwable $exception) {
            $export->exportError();
        }
        return $export->export();
    }

    protected function getTableField()
    {
        if (count($this->tableField) == 0) {
            $this->tableField = Db::connect($this->repository->getConnection())->getFields($this->repository->getTable());
        }
        return $this->tableField;
    }

    /**
     * @return Query|mixed
     */
    public function model()
    {
        return $this->builder;
    }
}
